<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>口径设置</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <div class="box-card">
        <div class="search-box">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText" v-if="btnSel"></el-input>
          <el-button type="primary" size="small" @click="add_new_question" v-if="btnAdd">
            <i></i>添加口径
          </el-button>
        </div>
        <el-tree
          ref="tree"
          :data="treeData"
          node-key="id"
          default-expand-all
          :render-content="renderContent"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
        ></el-tree>
        <el-row v-show="add_question_flag" :gutter="24" class="tree-root">
          <el-col :span="6">
            <input
              type="text"
              class="root-input"
              v-model="new_question_name"
              placeholder="请输入根节点名称"
            />
          </el-col>
          <el-col :span="5">
            <el-button
              size="mini"
              type="success"
              icon="el-icon-check"
              circle
              @click.stop="add_question_sure"
            ></el-button>
            <el-button size="mini" icon="el-icon-close" circle @click.stop="add_question_cancel"></el-button>
          </el-col>
        </el-row>
        <div class="card-line">
          <!-- 立即修改 -->
          <el-button type="primary" size="small" @click="onSubmit" v-if="btnEdit">立即修改</el-button>
          <!-- 重置 初始化表单数据 -->
          <el-button size="small" @click="reset" v-if="btnSel">重置</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { _debounce } from '@/public/debounce.js';
export default {
  name: 'category',
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    },
    // 搜索框输入
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  // 当前实例数据
  data () {
    return {
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,
      // 根节点ID
      rootId: 1,
      // 树节点ID
      treeId: 1,
      // 搜索框输入内容
      filterText: '',
      // 树结构数据
      treeData: [],
      // 根节点显示状态
      add_question_flag: false,
      // 根节点名称
      new_question_name: ''
    };
  },

  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取口径树
    this.getInfo();
  },

  methods: {
    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },
    // 提交修改
    onSubmit: _debounce(function () {
      let _this = this;
      let oneTrees = _this.$refs.tree.data;
      oneTrees.map(one => {
        if (one.children.length > 0) {
          one.disabled = true;
          let twoTrees = one.children;
          twoTrees.map(two => {
            if (two.children.length > 0) {
              two.disabled = true;
              let threeTrees = two.children;
              threeTrees.map(three => {
                if (three.children.length > 0) {
                  three.disabled = true;
                  let fourTrees = three.children;
                  fourTrees.map(four => {
                    if (four.children.length > 0) {
                      four.disabled = true;
                      let fiveTrees = fourTrees.children;
                      fiveTrees.map(five => {
                        if (five.children.length > 0) {
                          five.disabled = true;
                          let sixTrees = fiveTrees.children;
                          sixTrees.map(six => {
                            if (six.children.length > 0) {
                              six.disabled = true;
                              let servenTrees = sixTrees.children;
                              servenTrees.map(serven => {
                                if (serven.children.length > 0) {
                                  _this.$message({
                                    message: '设置节点过长，请重新设置',
                                    type: 'error'
                                  });
                                  return false;
                                }
                              });
                            }
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });

      let params = {
        rootId: _this.rootId,
        treeId: _this.treeId,
        tree: JSON.stringify(oneTrees)
      };

      _this.$nextTick(() => {
        // 修改口径树信息
        _this.$http.raw('api/insertTree', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            _this.$message({
              message: '修改成功！',
              type: 'success'
            });
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      });
    }, 200),

    // 获取口径树信息
    getInfo () {
      let _this = this;
      // 获取树
      _this.$http.post('api/findLastTree').then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          _this.treeData = JSON.parse(datas.tree);
          _this.rootId = datas.rootId;
          _this.treeId = datas.treeId;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 重置 重新初始化表单数据
    reset: _debounce(function () {
      let _this = this;
      _this.$http.post('api/findLastTree').then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          _this.treeData = JSON.parse(datas.tree);
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    }, 200),

    // 对树节点进行筛选时执行
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 显示根节点添加表单
    add_new_question () {
      this.add_question_flag = true;
    },

    // 确认添加根节点
    add_question_sure () {
      let _this = this;
      // 确定
      const nodeObj = {
        id: _this.rootId++,
        label: _this.new_question_name,
        isEdit: false,
        children: []
      };
      _this.treeData.push(nodeObj);
      _this.add_question_flag = false;
    },

    // 取消添加根节点
    add_question_cancel () {
      let _this = this;
      // 取消
      _this.add_question_flag = false;
      _this.new_question_name = '';
    },

    // 添加节点
    append (store, node, data) {
      let _this = this;
      // 新增数据
      const nodeapp = {
        id: _this.treeId++,
        label: '增加节点',
        isEdit: false,
        children: []
      };
      data.children.push(nodeapp);
      if (!node.expanded) {
        node.expanded = true;
      }
    },

    // 修改
    nodeEdit (ev, store, data) {
      let _this = this;
      data.isEdit = true;
      _this.$nextTick(() => {
        const $input = ev.target.parentNode.parentNode.querySelector('input') || ev.target.parentElement.parentElement.querySelector('input');
        if (!$input) {
          return '';
        } else {
          return $input.focus();
        }
      });
    },

    // 添加input输入框
    edit_sure (ev, data) {
      const $input =
        ev.target.parentNode.parentNode.querySelector('input') ||
        ev.target.parentElement.parentElement.querySelector('input');
      if (!$input) {
        return false;
      } else {
        data.label = $input.value;
        data.isEdit = false;
      }
    },

    // 节点删除
    nodeDelete (node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },

    // 显示编辑输入框
    showOrEdit (data) {
      if (data.isEdit) {
        return (
          <input
            type="text"
            value={data.label}
            on-blur={ev => this.edit_sure(ev, data)}
          />
        );
      } else {
        return <span className="node_labe">{data.label}</span>;
      }
    },

    // 结构树操作group node
    renderContent (h, { node, data, store }) {
      let _this = this;
      if (_this.btnEdit) {
        return (
          <span style="display:inline-block; width:100%;">
            <span style="float:left">{_this.showOrEdit(data)}</span>
            <span style="float:right">
              <i
                class="el-icon-edit"
                style="padding-right:20px; color:#409EFF"
                on-click={ev => _this.nodeEdit(ev, store, data)}
              >
              编辑
              </i>
              <i
                class="el-icon-delete"
                style="padding-right:20px; color:#F56C6C"
                on-click={() => _this.nodeDelete(node, data)}
              >
              删除
              </i>
              <i
                class="el-icon-plus"
                style="padding-right:20px; color:#85ce61"
                on-click={() => _this.append(store, node, data)}
              >
              添加
              </i>
            </span>
          </span>
        );
      } else {
        return (
          <span style="display:inline-block; width:100%;">
            <span style="float:left">{_this.showOrEdit(data)}</span>
          </span>
        );
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
